package com.kehutong.wwin.service.service;

import com.kehutong.common.urlconfig.FileUrlConfig;
import com.kehutong.common.util.Token;
import com.kehutong.wwin.service.entity.EmployeeMap;
import com.kehutong.wwin.service.util.ExcelUtil;
import com.kehutong.wwin.service.util.WwInHttpClient;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSON;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.JSONResult;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.IDGenerate;
import org.coraframework.util.Objects;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 导入数据服务类
 * @author: liukunlong
 * @date: 2021-04-02 10:42
 */
@WebService("/wwin-service/import")
public class ImportService {
    @Inject
    private WwInHttpClient httpClient;

    @Inject
    private ToKhtDepartmentService khtDepartmentService;

    @Inject
    private ToWwinEmployeeService toWwinEmployeeService;

    @Inject
    private ToWwinDepartmentService wwinDepartmentService;

    @Inject
    private JdbcSession jdbcSession;

    @Inject
    private FileUrlConfig fileUrlConfig;
    @ReqMapping("/uploadEmployee")
    public Object uploadEmployee(Token token, JSONObject jsonObject) throws Exception {
        String fileId =  jsonObject.getString("fileId");
        String code = jsonObject.getString("code"); //部门code

        byte[] bs = fileUrlConfig.download("/file/download", http->http.addParam("id", fileId));
        List<String[]> contents = ExcelUtil.readExcel(new ByteArrayInputStream(bs), 6);

        //批量转换客户通员工为企业微信员工数据
        List<EmployeeMap> wwinEmployeesList = new ArrayList<>(contents.size());
        List<String> userIds = new ArrayList<>(contents.size());
        for (int i = 0; i < contents.size(); i ++) {
            String[] content = contents.get(i);
            for (int j = 0; j < content.length - 2; j ++) {
                if (Objects.isEmpty(content[j])) {
                    return Result.error(0, "第" + i + "行：第" + j + "列号不能为空");
                }
            }

            //转换客户通员工为企业微信员工数据
            EmployeeMap entity = Pool.newInstance(EmployeeMap.class);
            entity.setId(content[0]);
            entity.setName(content[1]);
            entity.setMobile(content[2]);
            entity.setGender(content[3]);
            entity.setTelephone(content[4]);
            entity.setAddress(content[5]);
            //entity.setCompanyNo(companyNo);
            JSONArray khtDepartments=new JSONArray();
            khtDepartments.add(code);


            entity.setDepartments(JSONObject.parseArray(wwinDepartmentService.toWwId(khtDepartments).toString(),Integer.class));
            wwinEmployeesList.add(entity);
            userIds.add(entity.getId());
        }

        //如果导入的数据已经存在则提示那些用工已经存在
        JSONResult rs = check(userIds);
        if (!rs.isOk()){
            return rs;
        }

        //新增微信用户及映射关系


        List<String> errMsgs = new ArrayList<>();
        //客户通员工批量新增数组
        JSONArray khtEmployeesJsonArray=new JSONArray();
        for (int i = 0; i < wwinEmployeesList.size(); i ++) {
            final EmployeeMap wwinEmployeeMap = wwinEmployeesList.get(i);

            JSONObject userCreateResult = httpClient.postWWin("/cgi-bin/user/create", token, true, http->{
                JSONObject json = wwinEmployeeMap.toWwJson();
                http.setBody(json.toJSONString());
            });

            int errCode = userCreateResult.getIntValue("errcode");
            if (errCode != 0) {
                errMsgs.add("行:" + (i + 1) + ", 账号：" + wwinEmployeeMap.getId() + ", 错误:" + userCreateResult.getString("errmsg") + "\n");
            }

            //设置客户通员工编号
            wwinEmployeeMap.setKhtid(IDGenerate.nextId());

            //增加企业微信员工与客户通员工映射关系
            jdbcSession.insert(wwinEmployeeMap);




            //微信部门转客户通部门
            jsonObject.put("departments", khtDepartmentService.toKhtId(JSONArray.parseArray(JSON.toJSONString(wwinEmployeeMap.getDepartments()))));

            khtEmployeesJsonArray.add(wwinEmployeeMap.toKhtJson());
        }
        JSONObject saveBatch = httpClient.postKht("/basic/employee/service/saveBatch", token, http->{
            JSONObject body = new JSONObject();
            jsonObject.put("companyNo", token.getCompanyNo());
            jsonObject.put("companyName", token.getCompanyName());
            jsonObject.put("userList", khtEmployeesJsonArray);
            http.setBody(body.toJSONString());
        });

        //把上传失败的用户信息返回出来
        if (Objects.nonEmpty(errMsgs)) {
            return Result.error(0, String.join(",", errMsgs));
        }

        return Result.success();

    }

    public JSONResult check(List<String> userIds) {
        if (Objects.isEmpty(userIds)) {
            return Result.success();
        }

        List<EmployeeMap> employeeList = jdbcSession.findArray(EmployeeMap.class)
                .in("id", userIds)
                .exe();
        if (Objects.isEmpty(employeeList)) {
            return Result.success();
        }

        List<String> existUserids = employeeList.stream().map(EmployeeMap::getId).collect(Collectors.toList());
        return Result.error(0, "员工[" + String.join(",", existUserids) + "]已存在");
    }

}
